import requests
import json


class deepseekClientPostAnswer:
    ip = "127.0.0.1"
    port = 11434
    url = "api/chat"
    comUrl = f'http://{ip}:{port}/{url}'
    deepseekVersionMap = {0: "deepseek-r1:1.5b", 1: "deepseek-r1:7b",
                          2: "deepseek-r1:14b", 3: "deepseek-r1:32b"}

    def __init__(self):
        print("a deepseekClientPost class has been built")

    def postToDeepSeek(self, promot, furl=comUrl, deepseekv=2, isstream=True, deepthought=False, online=True):
        onlineOptions = {"web_search": online}

        # 重构模板逻辑
        if deepthought:
            prompt = f"<|user|><think>\n{promot}\n<|assistant|>\n"  # 用户侧标记+换行
        else:
            prompt = f"<|user|>{promot}\n<|assistant|>\n<think>"  # 助理侧标记

        headers = {"Content-Type": "application/json"}
        data = {
            "model": self.deepseekVersionMap[deepseekv],
            "messages": [{"role": "user", "content": prompt}],  # 注入处理后的prompt
            "stream": isstream,
            "options": onlineOptions
        }

        if not isstream:
            response = requests.post(furl, headers=headers, json=data,stream=False)
            if response.status_code == 200:
                result = response.json()
                reply = result["message"]["content"]
                # yield reply
                # print("DeepSeek回答：\n", reply)
                return reply
            else:
                print("请求失败，错误码：", response.status_code)
                print("错误信息：", response.text)
        else:
            response = requests.post(furl, headers=headers, json=data, stream=True)
            for chunk in response.iter_lines():
                if chunk:
                    yield json.loads(chunk.decode("utf-8"))["message"]["content"].encode('utf-8')

    def postToDeepSeekCom(self, promot, furl=comUrl, deepseekv=2, deepthought=True, online=True):
        onlineOptions = {"web_search": online}

        # 重构模板逻辑
        if deepthought:
            prompt = f"<|user|><think>\n{promot}\n<|assistant|>\n"  # 用户侧标记+换行
        else:
            prompt = f"<|user|>{promot}\n<|assistant|>\n<think>"  # 助理侧标记

        headers = {"Content-Type": "application/json"}
        data = {
            "model": self.deepseekVersionMap[deepseekv],
            "messages": [{"role": "user", "content": prompt}],  # 注入处理后的prompt
            # "stream": isstream,
            "options": onlineOptions
        }

        # if not isstream:
        response = requests.post(furl, headers=headers, json=data)
        if response.status_code == 200:
            result = response.json()
            reply = result["message"]["content"]
            return reply
            # print("DeepSeek回答：\n", reply)
        else:
            print("请求失败，错误码：", response.status_code)
            print("错误信息：", response.text)
        # else:
        #     response = requests.post(furl, headers=headers, json=data, stream=True)
        #     for chunk in response.iter_lines():
        #         if chunk:
        #             print(json.loads(chunk.decode("utf-8"))["message"]["content"])

    # def postToDeepSeekCom(self,promot,furl=comUrl, deepseekv = 2):
    #     headers = {
    #         "Content-Type": "application/json"
    #     }
    #     data = {
    #         "model": self.deepseekVersionMap[deepseekv],  # 与部署的模型名称一致
    #         "messages": [
    #             {"role": "user", "content": promot}
    #         ],
    #         "stream": False  # 关闭流式响应，直接获取完整结果
    #     }
    #
    #     # if not isstream:
    #     response = requests.post(furl, headers=headers, json=data)
    #     if response.status_code == 200:
    #         result = response.json()
    #         reply = result["message"]["content"]
    #         return reply
    #         # print("DeepSeek回答：\n", reply)
    #     else:
    #         print("请求失败，错误码：", response.status_code)
    #         print("错误信息：", response.text)
    #     # else:
    #     #     response = requests.post(furl, headers=headers, json=data, stream=True)
    #     #     for chunk in response.iter_lines():
    #     #         if chunk:
    #     #             print(json.loads(chunk.decode("utf-8"))["message"]["content"])
